package zt.song.config;

import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import zt.song.security.AccessDenied;
import zt.song.security.EnrityPointHandler;
import zt.song.security.LogFaileHandler;

/**
 * @Author 宋伟宁
 * @Date 2023/11/23
 * @Version 1.0
 **/
@EnableWebSecurity
@Configuration
public class SecurityConfig {


    private static final String[] URL_WHITELIST = {
       "/login","/logout"
    };

    @Resource
    private LogFaileHandler logFaileHandler;

    @Resource
    private EnrityPointHandler enrityPointHandler;
    @Resource
    private AccessDenied accessDenied;
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        // 放过白名单
         http.authorizeHttpRequests( resp->
                   resp.requestMatchers(URL_WHITELIST).permitAll()
                           .requestMatchers("/student/list").hasAnyRole("admin","abc")
                           .requestMatchers("/student/**").hasAnyRole("admin")
                           .anyRequest().authenticated()
                 );
         //自定义登录页面
         http.formLogin( form->
                  form.loginPage("/login").permitAll()
                  //登录成功后处理

                          .defaultSuccessUrl("/index")
                          .failureHandler(this.logFaileHandler)
                  //
                 );

        // 定义异常处理
         //403
         http.exceptionHandling(e-> e.accessDeniedHandler(this.accessDenied));
        //未登录
        http.exceptionHandling(e-> e.authenticationEntryPoint(this.enrityPointHandler));
        // 关闭session
       // http.sessionManagement(e-> e.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
        // 关闭csrf
        http.csrf(Customizer.withDefaults());

        return  http.build();
    }
}
